package com.vueapi.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.vueapi.constant.ErrorCodeEnum;
import com.vueapi.domain.HjUser;
import com.vueapi.exception.TokenException;
import com.vueapi.service.HjUserService;
import com.vueapi.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname LoginInterceptor
 * @Description TODO
 * @Created by 赵宏建
 * @Date 2022/9/20 16:23
 * @Version 1.0.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private HjUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取TOKEN
        String token = request.getHeader("Authorization");

        // 如果 token 为 null，就直接返回
        if(token == null){
            throw new TokenException(ErrorCodeEnum.TOKEN_NULL.getCode() ,ErrorCodeEnum.TOKEN_NULL.getMsg());
        }

        // 验证 TOKEN 合法性
        if(!JwtUtil.validateToken(token)){
            throw new TokenException(ErrorCodeEnum.TOKEN_ERROR.getCode(), ErrorCodeEnum.TOKEN_ERROR.getMsg());
        }

        // 验证 TOKEN 是否过期
        if(JwtUtil.isTokenExpired(token)){
            throw new TokenException(ErrorCodeEnum.TOKEN_OUT.getCode(), ErrorCodeEnum.TOKEN_OUT.getMsg());
        }

        String usernameFromToken = JwtUtil.getUsernameFromToken(token);
        // 验证 TOKEN 中存在的用户信息是否有效
        HjUser hjUser = userService.getOne(new LambdaQueryWrapper<HjUser>().eq(HjUser::getUsername, usernameFromToken));
        if(hjUser == null){
            throw new TokenException(ErrorCodeEnum.ACCOUNT_NULL.getCode(), ErrorCodeEnum.ACCOUNT_NULL.getMsg());
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
